<!DOCTYPE html>
<html lang="en">
<style>
    video {
        width: 100%;
        height: auto;
        min-width: 100px; /* 设置最小宽度 */
        min-height: 100px;
    }

    #switchCameraButton {
        padding: 12px 24px;
        background-color: #007BFF;
        color: white;
        border: none;
        border-radius: 4px;
        font-size: 16px;
        float: right;
    }

    #roomIdInput {
        padding: 12px;
        border: 1px solid #ccc;
        border-radius: 4px;
        margin-right: 10px;
    }

    #joinRoomButton {
        padding: 12px 24px;
        background-color: #28a745;
        color: white;
        border: none;
        border-radius: 4px;
        font-size: 16px;
    }
</style>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>手机摄像头检测</title>
</head>

<body>
    <!--<h1>1.0.1</h1>-->
    <video id="localVideo" autoplay muted playsinline></video>
    <button id="switchCameraButton">切换摄像头</button>
    <!-- <input type="text" id="roomIdInput" placeholder="请输入房间号">
    <button id="joinRoomButton">加入房间</button> -->
    <!--<video id="remoteVideo" autoplay playsinline></video>-->
    <script src="/socket.io/socket.io.js"></script>
</body>

</html>

<script>
    // const socket = io('https://192.168.0.117:3000');
    const localVideo = document.getElementById('localVideo');
    // const roomIdInput = document.getElementById('roomIdInput');
    // const joinRoomButton = document.getElementById('joinRoomButton');
    // const remoteVideo = document.getElementById('remoteVideo');

    let peerConnection;
    let cameraFacingMode = 'user';
    let roomId;

    // const configuration = {
    //     iceServers: [
    //         { urls: 'stun:stun.l.google.com:19302' },
    //         { urls: 'stun:stun1.l.google.com:19302' },
    //         { urls: 'stun:stun2.l.google.com:19302' }
    //     ]
    // };

    // 调用切换摄像头的函数
    switchCameraButton.addEventListener('click', switchCamera);

    // 添加一个切换摄像头的函数
    async function switchCamera() {
        // 切换摄像头朝向
        cameraFacingMode = cameraFacingMode === 'user' ? 'environment' : 'user';
        // 停止当前的媒体流
        const currentStream = localVideo.srcObject;
        if (currentStream) {
            const tracks = currentStream.getTracks();
            tracks.forEach(track => track.stop());
        }
        // 重新获取新的媒体流
        await getLocalStream();
    }

    // 获取本地摄像头流
    async function getLocalStream() {
        try {
            let stream;
            if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                try {
                    stream = await navigator.mediaDevices.getUserMedia({
                        video: { facingMode: cameraFacingMode },
                        audio: false
                    });
                    // alert('Camera permission granted and stream obtained')
                    console.log('Camera permission granted and stream obtained');
                } catch (permissionError) {
                    console.error('Camera permission denied:', permissionError);
                    // alert(permissionError)
                    return null;
                }
            } else {
                alert('getUserMedia is not supported in this browser');
                throw new Error('getUserMedia is not supported in this browser');
            }

            if (stream) {
                if ('srcObject' in localVideo) {
                    localVideo.srcObject = stream;
                } else {
                    localVideo.src = window.URL.createObjectURL(stream);
                }
                localVideo.addEventListener('loadedmetadata', async () => {
                    try {
                        await localVideo.play();
                        console.log('Video started playing');
                    } catch (playError) {
                        console.error('Error playing video:', playError);
                    }
                });
            }

            return stream;
        } catch (error) {
            console.error('Error accessing media devices:', error);
            alert(error);
            return null;
        }
    }

    // 创建 RTCPeerConnection 并添加本地流
    async function createPeerConnection() {
        const localStream = await getLocalStream();
        peerConnection = new RTCPeerConnection(configuration);

        localStream.getTracks().forEach(track => {
            peerConnection.addTrack(track, localStream);
        });

        peerConnection.onicecandidate = (event) => {
            if (event.candidate) {
                socket.emit('ice-candidate', roomId, event.candidate);
            }
        };

        // peerConnection.ontrack = (event) => {
        //     remoteVideo.srcObject = event.streams[0];
        // };
    }

    // // 发起呼叫
    // async function startCall() {
    //     await createPeerConnection();
    //     const offer = await peerConnection.createOffer();
    //     await peerConnection.setLocalDescription(offer);
    //     socket.emit('offer', roomId, offer);
    // }

    // // 处理接收到的 offer
    // socket.on('offer', async (offer) => {
    //     await createPeerConnection();
    //     await peerConnection.setRemoteDescription(offer);
    //     const answer = await peerConnection.createAnswer();
    //     await peerConnection.setLocalDescription(answer);
    //     socket.emit('answer', roomId, answer);
    // });

    // // 处理接收到的 answer
    // socket.on('answer', async (answer) => {
    //     await peerConnection.setRemoteDescription(answer);
    // });

    // // 处理接收到的 ICE 候选信息
    // socket.on('ice-candidate', (candidate) => {
    //     peerConnection.addIceCandidate(new RTCIceCandidate(candidate));
    // });

    // // 加入房间
    // joinRoomButton.addEventListener('click', async () => {
    //     roomId = roomIdInput.value;
    //     if (roomId) {
    //         socket.emit('join-room', roomId);
    //         await startCall();
    //     }
    // });
</script>